package net.sumcraft.mythicmobitemhandler.commands;

import io.lumine.xikage.mythicmobs.items.ItemManager;
import io.lumine.xikage.mythicmobs.items.MythicItem;
import net.sumcraft.mythicmobitemhandler.MythicMobItemHandler;
import net.sumcraft.mythicmobitemhandler.util.$;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import pw.yumc.YumCore.tellraw.Tellraw;

import java.io.File;
import java.util.Iterator;
import java.util.List;

public class ItemSaverCommand implements CommandExecutor {


    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        ItemManager itemManager = MythicMobItemHandler.mythicMobItemHandler.getItemManager();
        List<File> itemFiles = MythicMobItemHandler.mythicMobItemHandler.getItemFiles();
        if (!sender.isOp()) {
            return false;
        }
        //空参数 发送帮助信息
        if (args.length == 0) {
            helpMessage(sender);
            return true;
        }

        if (args.length == 1) {
            //its list 命令
            if ("list".equalsIgnoreCase(args[0])) {
                StringBuilder stringBuilder = new StringBuilder();
                int showAmount = 30;
                int totalAmount = itemManager.getItemNames().size();
                int index = totalAmount > showAmount ? showAmount : totalAmount;
                Iterator<String> iterator = itemManager.getItemNames().iterator();
                int count = 0;
                while (iterator.hasNext()) {
                    if (count < index) {
                        String string = iterator.next();
                        stringBuilder.append("§c").append(string).append("§7,");
                    } else {
                        break;
                    }
                    count++;
                }
                String msg01 = "§a已显示: §7" + showAmount + " §a个物品, 还有: §7"
                        + (totalAmount - showAmount) + " §a个物品未显示 ";
                String msg02 = "§a已显示: §7" + totalAmount + " §7个物品";
                sender.sendMessage(stringBuilder.toString());
                sender.sendMessage(totalAmount > showAmount ? msg01 : msg02);
                return true;
            }
            // its files
            if ("files".equalsIgnoreCase(args[0])) {
                Bukkit.dispatchCommand(sender, "its files 1");
                return true;
            }
            //its help
            if ("help".equalsIgnoreCase(args[0])) {
                helpMessage(sender);
                return true;
            }
            //its reload
            if ("reload".equalsIgnoreCase(args[0])) {
                MythicMobItemHandler.mythicMobItemHandler.load();
                sender.sendMessage("插件重载成功");
                return true;
            }

        }
        if (args.length == 2) {
            //its files [pages]
            if ("files".equalsIgnoreCase(args[0])) {
                //判断参数是否为数字
                if (!$.canParseInt(args[1])) {
                    sender.sendMessage("页码必须为数字");
                    return false;
                }
                return pagingFiles(sender, args[1], itemFiles);
            }
            //its get [name] 会替换PAPI变量
            if ("get".equalsIgnoreCase(args[0])) {
                if (!(sender instanceof Player)) {
                    sender.sendMessage("该命令必须由玩家执行");
                }
                Player player = (Player) sender;
                if (!itemManager.getItemNames().contains(args[1])) {
                    player.sendMessage("该物品不存在");
                    return false;
                }
                ItemStack itemStack = itemManager.getItemStack(args[1]);
                $.replacePlaceholder(itemStack, player);
                $.randomLore(itemStack);
                $.replaceColreCode(itemStack);
                player.getInventory().addItem(itemStack);
                player.updateInventory();
                return false;
            }
            //its list [filename]
            if ("list".equalsIgnoreCase(args[0])) {
                boolean hasFile = false;
                for (File f : itemFiles
                ) {
                    if (f.getName().equals(args[1])) {
                        hasFile = true;
                        break;
                    }
                }
                if (!hasFile) {
                    sender.sendMessage("文件 " + args[1] + " 不存在");
                    return false;
                }
                String cmd = "its list " + args[1] + " 1";
                Bukkit.dispatchCommand(sender, cmd);
                return true;
            }
        }
        if (args.length == 3) {
            //its list [filename] [pageNum]
            if ("list".equalsIgnoreCase(args[0])) {
                if (!$.canParseInt(args[2])) {
                    sender.sendMessage("页码必须为数字");
                    return false;
                }
                int pageNum = Integer.valueOf(args[2]);
                boolean hasFile = false;
                for (File f : itemFiles
                ) {
                    if (f.getName().equals(args[1])) {
                        hasFile = true;
                        break;
                    }
                }
                if (!hasFile) {
                    sender.sendMessage("文件 " + args[1] + " 不存在");
                    return false;
                }
                sender.sendMessage("§6文件 §5" + args[1] + "§6中的物品有:");
                sender.sendMessage("§a====================================");
                List<MythicItem> itemStacks = MythicMobItemHandler.mythicMobItemHandler.getItemMap().get(args[1]);
                return pagingItems(sender, pageNum, itemStacks, args[1]);
            }
            //its give [name] [player] 会替换PAPI变量
            if ("give".equalsIgnoreCase(args[0])) {
                Player p = Bukkit.getPlayer(args[2]);
                if (!itemManager.getItemNames().contains(args[1])) {
                    p.sendMessage("该物品不存在");
                    return false;
                }
                ItemStack itemStack = itemManager.getItemStack(args[1]);
                $.replacePlaceholder(itemStack, p);
                $.randomLore(itemStack);
                $.replaceColreCode(itemStack);
                p.getInventory().addItem(itemStack);
                p.updateInventory();
                return false;

            }
            // its save [name] [filename] 存入物品
            if ("save".equalsIgnoreCase(args[0])) {

                if (!(sender instanceof Player)) {
                    sender.sendMessage("该命令必须由玩家执行");
                }
                Player player = (Player) sender;
                if (itemManager.getItemNames().contains(args[1])) {
                    player.sendMessage("该物品已存在");
                    return false;
                }
                String cmd = "mythicmobs i import " + args[1] + " " + args[2];
                Bukkit.dispatchCommand(player, cmd);
            }
        }
        if (args.length == 4) {
            //its give [name] [amount] [player] 会替换PAPI变量
            if ("give".equalsIgnoreCase(args[0])) {
                Player p = Bukkit.getPlayer(args[3]);
                if (!itemManager.getItemNames().contains(args[1])) {
                    p.sendMessage("该物品不存在");
                    return false;
                }
                ItemStack itemStack = itemManager.getItemStack(args[1]);
                itemStack = $.replacePlaceholder(itemStack, p);
                itemStack.setAmount(Integer.parseInt(args[2]));
                $.randomLore(itemStack);
                $.replaceColreCode(itemStack);
                p.getInventory().addItem(itemStack);
                p.updateInventory();
                return false;
            }
        }
        if (args.length == 5) {
            //its give [name] [amount] [level] [player]  会替换PAPI变量,并且字符串中的$level$会被替换为level;
            if ("give".equalsIgnoreCase(args[0])) {
                Player p = Bukkit.getPlayer(args[4]);
                if (!itemManager.getItemNames().contains(args[1])) {
                    p.sendMessage("该物品不存在");
                    return false;
                }
                ItemStack itemStack = itemManager.getItemStack(args[1]);
                $.replaceLevel(itemStack, Integer.parseInt(args[3]));
                itemStack = $.replacePlaceholder(itemStack, p);
                $.randomLore(itemStack);
                $.replaceColreCode(itemStack);
                itemStack.setAmount(Integer.parseInt(args[2]));
                p.getInventory().addItem(itemStack);
                p.updateInventory();
                return false;
            }
            //its drop [name] [amount] [level] [player] 在玩家位置生成一个物品
            if ("drop".equalsIgnoreCase(args[0])) {
                Player p = Bukkit.getPlayer(args[4]);
                if (!itemManager.getItemNames().contains(args[1])) {
                    p.sendMessage("该物品不存在");
                    return false;
                }
                ItemStack itemStack = itemManager.getItemStack(args[1]);
                $.replaceLevel(itemStack, Integer.parseInt(args[3]));
                itemStack = $.replacePlaceholder(itemStack, p);
                $.randomLore(itemStack);
                $.replaceColreCode(itemStack);
                itemStack.setAmount(Integer.parseInt(args[2]));
                p.getWorld().dropItem(p.getLocation().add(0, 1, 0), itemStack);
                return false;
            }
        }

        return false;
    }

    /**
     * @param sender     命令执行人
     * @param pageNum    命令参数
     * @param itemStacks 物品列表
     * @param fileName   文件名称
     * @return
     */
    private boolean pagingItems(CommandSender sender, int pageNum, List<MythicItem> itemStacks, String fileName) {

        int pageSize = 10;
        int size = itemStacks.size();
        int totalPage = size % pageSize > 0 ? size / pageSize + 1 : size / pageSize;
        //判断页码是否超过totalPage
        if (pageNum > totalPage) {
            sender.sendMessage("没有这么多页数, 总计页数为: " + totalPage);
            return false;
        }
        //pageNum页的起始index  终止index 为 (pageSize*pageNum)-1
        int lastIndex = pageNum == totalPage ? size - 1 : (pageSize * pageNum) - 1;
        for (int i = pageSize * (pageNum - 1); i <= lastIndex; i++) {
            Tellraw tellraw = Tellraw.create();
            MythicItem mythicItem = itemStacks.get(i);
            String itemName = mythicItem.getDisplayName();
            String cmd = "/mmits get " + mythicItem.getInternalName();
            tellraw.text("§e" + String.valueOf(i + 1) + ".§b " + itemName).cmd_tip(cmd, $.replaceColorCode(mythicItem.getLore()).toArray(new String[mythicItem.getLore().size()])).send(sender);
            //最后一个
            if (i == lastIndex) {
                Tellraw tellraw1 = Tellraw.create();
                String nextPage = "/its list " + fileName + " " + (pageNum + 1);
                String previousPage = "/its list " + fileName + " " + (pageNum - 1);
                sender.sendMessage("§a====================================");
                //第一页
                if (pageNum == 1) {
                    if (pageNum != totalPage) {
                        tellraw1.text("                            ").
                                then("§7§l§n下一页").cmd_tip(nextPage, "点击查看下一页").send(sender);
                    }
                    return true;
                }
                //最后一页
                if (pageNum == totalPage) {
                    tellraw1.text("§7§l§n上一页").cmd_tip(previousPage, "点击查看上一页").send(sender);
                    return true;
                }
                tellraw1.text("§7§l§n上一页").cmd_tip(previousPage, "点击查看上一页")
                        .then("                ").then("§7§l§n下一页").cmd_tip(nextPage, "点击查看下一页")
                        .send(sender);
                return true;
            }
        }
        return false;
    }

    /**
     * 将files分页输出
     *
     * @param sender    命令执行人
     * @param arg       命令参数
     * @param itemFiles 物品列表
     * @return
     */
    private Boolean pagingFiles(CommandSender sender, String arg, List<File> itemFiles) {
        int pageNum = Integer.valueOf(arg);
        int pageSize = 10;
        int size = itemFiles.size();
        int totalPage = size % pageSize > 0 ? size / pageSize + 1 : size / pageSize;
        //判断页码是否超过totalPage
        if (pageNum > totalPage) {
            sender.sendMessage("没有这么多页数, 总计页数为: " + totalPage);
            return false;
        }
        //pageNum页的起始index  终止index 为 (pageSize*pageNum)-1
        int lastIndex = pageNum == totalPage ? size - 1 : (pageSize * pageNum) - 1;
        for (int i = pageSize * (pageNum - 1); i <= lastIndex; i++) {
            //首行
            if (i == pageSize * (pageNum - 1)) {
                sender.sendMessage("§a===========" + "§6文件列表(§7" + pageNum + "/" + totalPage + "§6)" + "§a===========");
            }
            Tellraw tellraw = Tellraw.create();
            String filename = itemFiles.get(i).getName();
            List<MythicItem> itemlist = MythicMobItemHandler.mythicMobItemHandler.getItemMap().get(filename);
            String cmd = "/its list " + filename;
            tellraw.text("§e" + String.valueOf(i + 1) + ".§b " + itemFiles.get(i).getName()).cmd_tip(cmd, tipNameList(itemlist)).send(sender);
            //最后一个
            if (i == lastIndex) {
                Tellraw tellraw1 = Tellraw.create();
                String nextPage = "/its files " + (pageNum + 1);
                String previousPage = "/its files " + (pageNum - 1);
                sender.sendMessage("§a====================================");
                //第一页
                if (pageNum == 1) {
                    if (pageNum != totalPage) {
                        tellraw1.text("                            ").
                                then("§7§l§n下一页").cmd_tip(nextPage, "点击查看下一页").send(sender);
                    }
                    return true;
                }
                //最后一页
                if (pageNum == totalPage) {
                    tellraw1.text("§7§l§n上一页").cmd_tip(previousPage, "点击查看上一页").send(sender);
                    return true;
                }
                tellraw1.text("§7§l§n上一页").cmd_tip(previousPage, "点击查看上一页")
                        .then("                ").then("§7§l§n下一页").cmd_tip(nextPage, "点击查看下一页")
                        .send(sender);
                return true;
            }
        }
        return false;
    }

    /**
     * 输出帮助信息
     *
     * @param sender
     */
    private void helpMessage(CommandSender sender) {
        if (sender instanceof Player) {
            sender.sendMessage("§6/mmits get <物品名> §7获得指定道具");
            sender.sendMessage("§6/mmits give <物品名> <玩家名> §7给予指定玩家默认为1");
            sender.sendMessage("§6/mmits save <物品名> <文件名> §7将物品存到mm指定文件夹");
            sender.sendMessage("§6/mmits give <物品名> <数量> <玩家名> §7给予指定数量指定玩家");
            sender.sendMessage("§6/mmits give <物品名> <数量> <level> <玩家名> §7给予指定数量指定玩家,并替换物品的中的$level$");
            sender.sendMessage("§6/mmits drop <物品名> <数量> <level> <玩家名> §7在玩家位置掉落物品,并替换物品的中的$level$");
            sender.sendMessage("§6/mmits list §7列出所有物品");
            sender.sendMessage("§6/mmits list <文件名> §7列出目标文件中所有物品");
            sender.sendMessage("§6/mmits files §7列出所有物品文件名");
            sender.sendMessage("§6/mmits reload §7重载配置文件,如果更新了mm物品请先mm reload后在执行该命令");
        } else {
            sender.sendMessage("§6/mmits give <物品名> <玩家名> §7给予指定玩家默认为1");
            sender.sendMessage("§6/mmits give <物品名> <数量> <玩家名> §7给予指定数量指定玩家");
            sender.sendMessage("§6/mmits give <物品名> <数量> <level> <玩家名> §7给予指定数量指定玩家,并替换物品的中的$level$");
            sender.sendMessage("§6/mmits drop <物品名> <数量> <level> <玩家名> §7在玩家位置掉落物品,并替换物品的中的$level$");
            sender.sendMessage("§6/mmits list §7列出所有物品");
            sender.sendMessage("§6/mmits list <文件名> §7列出目标文件中所有物品");
            sender.sendMessage("§6/mmits files §7列出所有物品文件名");
            sender.sendMessage("§6/mmits reload §7重载配置文件,如果更新了mm物品请先mm reload后在执行该命令");
        }
    }

    private String[] tipNameList(List<MythicItem> list) {
        int index = list.size() > 5 ? 5 : list.size();
        String[] strings = new String[index + 4];
        strings[0] = "§6包含以下物品: ";
        for (int i = 0; i < index; i++) {
            strings[i + 1] = "§e" + String.valueOf(i) + "§7. §r" + list.get(i).getDisplayName();
        }
        strings[index + 1] = "§a共 §c" + list.size() + " §a个物品";
        strings[index + 2] = "§c";
        strings[index + 3] = "§7§o§n点击查看";
        return strings;
    }
}
